﻿using System;
using System.Linq;
using Citi.Scheduler.Domain;
using System.Collections.Generic;

namespace Citi.Scheduler.Wcf
{
    public class Schedule : ISchedule
    {
        public void ExecuteRoutineOnDemandById(int routineId, IDictionary<string, string> parameters)
        {
            var routine = new Routine().SelectById<Routine>(routineId);
            InsertOnDemand(routine, parameters);
        }

        public void ExecuteRoutineOnDemandByName(string routineFullName, IDictionary<string, string> parameters )
        {
            var routine = new Routine().GetRoutineByName(routineFullName);
            InsertOnDemand(routine, parameters);
        }

        private void InsertOnDemand(Routine routine, IDictionary<string, string> parameters)
        {
            if (routine == null || !routine.Active)
                throw new Exception("Routine does not exist or is inactive");

            if (parameters != null)
            {
                foreach (var parameter in parameters)
                {
                    var parameterSaved = routine.RoutineParameters.FirstOrDefault(x => x.Name == parameter.Key);

                    if (parameterSaved == null)
                    {
                        parameterSaved = new RoutineParameter
                        {
                            Application = new Application().GetByAbbreviation("SCH"),
                            Routine = routine,
                            Name = parameter.Key
                        };
                    }

                    parameterSaved.Value = parameter.Value;
                    parameterSaved.Save(parameterSaved);
                }
            }

            var onDemand = new RoutineOnDemand { Date = DateTime.Now, RequesterId = routine.ResponsibleId, RoutineId = routine.Id };
            onDemand.Save(onDemand);

            new RoutineSchedule().SendOnDemandRoutines();
        }
    }
}